//
//  String+YMHash.swift
//  YMToolKit
//
//  Created by YDWY on 2017/4/20.
//  Copyright © 2017年 YDWY. All rights reserved.
//

import Foundation


extension String{
    
    
    
    
    /// MD5 加密
    
    /**
     *  计算MD5散列结果
     *
     *  终端测试命令：
     *  @code
     *  md5 -s "string"
     *  @endcode
     *
     *  <p>提示：随着 MD5 碰撞生成器的出现，MD5 算法不应被用于任何软件完整性检查或代码签名的用途。<p>
     *
     *  @return 32个字符的MD5散列字符串
     */
//    var ym_md5String : String! {
//        
//        let str = self.cString(using: String.Encoding.utf8)
//        let strLen = CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8))
//        let digestLen = Int(CC_MD5_DIGEST_LENGTH)
//        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
//        
//        CC_MD5(str!, strLen, result)
//        
//        return self.stringForm(bytes: result, length: digestLen)
//    }
//
    
    /**
     *  计算SHA1散列结果
     *
     *  终端测试命令：
     *  @code
     *  echo -n "string" | openssl sha -sha1
     *  @endcode
     *
     *  @return 40个字符的SHA1散列字符串
     */
    
//    var ym_sha1String : String! {
//        
//        let str = self.cString(using: String.Encoding.utf8)
//        let strLen = CC_LONG(self.lengthOfBytes(using: String.Encoding.utf8))
//        let digestLen = Int(CC_SHA1_DIGEST_LENGTH)
//        let result = UnsafeMutablePointer<CUnsignedChar>.allocate(capacity: digestLen)
//        
//        CC_MD5(str!, strLen, result)
//        
//        return self.stringForm(bytes: result, length: digestLen)
//        
//    }
    
    
    
    
    //MARK: - 助手方法
    
    func stringForm(bytes :UnsafePointer<CUnsignedChar> , length :Int) -> String {
        let strM = NSMutableString()
        for  i in 0..<length {
            strM.appendFormat("%02x", bytes[i]);
        }
        return String(format:strM as String)
    }
    
    
    
    
    
    
}
